import express from 'express';
import nodemailer from 'nodemailer';
import globalCache from '../../cache.js';
import mailConfig from '../../smtp.js';
import regCheck from '../../util/checkReg.js';
import { generateVerify } from '../../util/generalCode.js';

let router = express.Router();

router.post('/send', (req, res, next) => {

  let {email,text,subject} = req.body
  console.log('req.body: ', req.body);
  if (globalCache.getCache('email',email)) {
    res.json(req.app.locals.error('验证码尚未过期,请间隔1分钟重新发送'))
    return
  }
  const verifyCode = generateVerify(6)
  // 邮箱注册
  const params = {
    to: email,
    subject: subject || '验证码验证',
    verifyCode,
    text: (text || '注册验证码：') + verifyCode
  }
  text += '<b>' + verifyCode + '</b>'
  handleSendEmail(params).then((result) => {
    globalCache.setCache('email',email,{value: verifyCode},1000*60*5)
    res.send(req.app.locals.success(`验证码已发送至邮箱，请查收`))
  }).catch((err) => {
    res.send(req.app.locals.error(err.message))
    console.log('err: ', err);
  });

})


/**
 * @param {String} to  // 邮箱列表
 * @param {String} subject  // 邮箱主题
 * @param {String} text  // 邮箱内容，支持html格式
 */

const handleSendEmail = (param) => {

  return new Promise((resolve, reject) => {

    let { to, subject, text='', verifyCode } = param
    if (!to) {
      reject(new Error('请输入邮箱'))
    }
    const email_list = to.split(',')

    const isCheckEmail = email_list.every((item) => {
      return regCheck('email').test(item)
    })

    if (!isCheckEmail) {
      reject('email 格式错误')
    }

    nodemailer.createTestAccount((err, account) => {
      if (err) reject(err)
      let transporter = nodemailer.createTransport({
        service: '163', // no need to set host or port etc.
        secure: true,
        auth: {
          user: mailConfig.account.user,
          pass: mailConfig.account.pass
        }
      })
      let mailOptions = {
        from: `"YIFAN亿帆团队" <${mailConfig.account.user}>`, // sender address
        to, // list of receivers
        subject, // Subject line
        // text: 'Hello world?', // plain text body
        html: text // html body
      };

      console.log('mailOptions: ', mailOptions);
      transporter.sendMail(mailOptions, (err, info) => {
        if (err) reject(err)
        resolve(text)
      })

    })

  })
}
export { handleSendEmail };
export default router